package ch.zbw.sysventory.server.control;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import ch.zbw.sysventory.server.model.ComputerScan;
import ch.zbw.sysventory.server.model.ComputerScanResult;
import ch.zbw.sysventory.server.service.ComputerScanResultService;
import ch.zbw.sysventory.server.service.ComputerScanService;

@Component
@Controller
public class ScanResultController {

	@Autowired
	private ComputerScanService computerScanService;

	@Autowired
	private ComputerScanResultService computerScanResultService;

	@RequestMapping(value = "/scanresultlist", method = RequestMethod.GET)
	public String redirectToLastResults(Model model) {
		return "redirect:/scanresultlist/latest";
	}

	@RequestMapping(value = "/scanresultlist/{scanId}", method = RequestMethod.GET)
	public ModelAndView listResults(Model model, @PathVariable("scanId") String scanId) {
		List<ComputerScan> scanList = this.computerScanService.list();
		model.addAttribute("scan_list", scanList);
		ComputerScan selectedScan = scanList.get(0);
		if ("latest".equals(scanId)) {
			selectedScan = scanList.get(0);
		} else {
			Long scanIdLong = Long.valueOf(scanId);
			selectedScan = this.computerScanService.get(scanIdLong);
		}
		model.addAttribute("selectedScan", selectedScan);
		model.addAttribute("scanresult_list", this.computerScanResultService.listByComputerScan(selectedScan));
		return new ModelAndView("scanresultlist");
	}

	@RequestMapping(value = "/scan/{id}", method = RequestMethod.GET)
	public ModelAndView showUser(Model model, @PathVariable("id") String id) {
		ComputerScanResult computerScanResult = this.computerScanResultService.get(Long.valueOf(id));
		model.addAttribute("scan", computerScanResult);
		List<ComputerScanResult> scans = this.computerScanResultService.listByComputer(computerScanResult.getComputer());
		Collections.sort(scans);
		model.addAttribute("scan_list", scans);
		return new ModelAndView("scan");
	}
}
